package com.gexiaobao.pigeon.ui.fragment.mall

import android.annotation.SuppressLint
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import androidx.appcompat.widget.AppCompatImageView
import androidx.appcompat.widget.AppCompatTextView
import androidx.recyclerview.widget.LinearLayoutManager
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.eventViewModel
import com.gexiaobao.pigeon.app.ext.init
import com.gexiaobao.pigeon.app.model.bean.ConfirmAnOrderResponse
import com.gexiaobao.pigeon.app.model.bean.ReasonListBean
import com.gexiaobao.pigeon.app.model.param.AddOrReGoodsParam
import com.gexiaobao.pigeon.app.model.param.RefundReturnParam
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.SettingUtil
import com.gexiaobao.pigeon.app.util.StatusBarUtil
import com.gexiaobao.pigeon.app.util.Util
import com.gexiaobao.pigeon.app.weight.recycleview.SpaceItemDecoration
import com.gexiaobao.pigeon.databinding.FragmentConfirmOrderProgressBinding
import com.gexiaobao.pigeon.ui.adapter.ConfirmOrderAdapter
import com.gexiaobao.pigeon.ui.adapter.ReturnGoodsReasonAdapter
import com.gexiaobao.pigeon.ui.dialog.RxDialogDefault
import com.gexiaobao.pigeon.ui.mall.MallViewModel
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.yanzhenjie.recyclerview.SwipeRecyclerView
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.navigateAction
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat


/**
 * @Author      : hxw
 * @Date        : 2023/7/4 16:06
 * @Describe    : 确认订单（进行中）
 */
class FragmentConfirmOrderProgress : BaseFragment<MallViewModel, FragmentConfirmOrderProgressBinding>() {

    private var expressNo: String = ""
    private val mAdapter: ConfirmOrderAdapter by lazy { ConfirmOrderAdapter(arrayListOf()) }
    private val mAdapterReason: ReturnGoodsReasonAdapter by lazy { ReturnGoodsReasonAdapter(arrayListOf()) }
    private var mOrderId = ""
    private var totalPrice = ""
    private var mOrderStatus = -1
    private lateinit var dialogBottom: BottomSheetDialog//退款原因

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        activity?.let { StatusBarUtil.setLightMode(it) }
        activity?.let { StatusBarUtil.setColor(it, Color.TRANSPARENT, 0) }
    }

    override fun initView(savedInstanceState: Bundle?) {
        mOrderId = arguments?.getString("orderId").toString()//170

        mDatabind.recyclerViewOrderDetail.init(LinearLayoutManager(context), mAdapter).addItemDecoration(
            SpaceItemDecoration(0, Util.dp2px(context, 10f))
        )
        mDatabind.recyclerViewOrderDetail.adapter = mAdapter

        mAdapter.setOnReturnGoodsClickListener(object : ConfirmOrderAdapter.OnBtnReturnClickListener {
            override fun onBtnReturnClick(position: Int, goodsId: Int, orderId: Int, orderStatus: Int, shopId: Int, shopOrderId: Int) {
                when (orderStatus) {
                    2 -> {
                        showBottomDialogReason(goodsId, orderId, shopId)
                    }

                    3 -> {
                        nav().navigateAction(R.id.action_to_fragment_return_of_goods, Bundle().apply {
                            putInt("orderId", orderId)
                            putInt("shopUserId", shopId)
                            putString("goodsId", goodsId.toString())
                        })
                    }

                    11, 13, 14 -> {
                        nav().navigateAction(R.id.action_to_fragment_return_detail, Bundle().apply {
                            putInt("orderId", orderId)
                            putInt("shopId", shopId)
                            putString("goodsId", goodsId.toString())
                        })
                    }

                    15 -> {
                        nav().navigateAction(R.id.action_to_fragment_send_goods_out, Bundle().apply {
                            putInt("shopId", shopId)
                            putInt("orderId", shopOrderId)
                            putInt("childOrderId", orderId)
                        })
                    }
                }
            }
        })
    }

    override fun onResume() {
        super.onResume()
        onRefresh()
    }

    private fun onRefresh() {
        showLoadingAntiShake(getString(R.string.loading))
        mViewModel.getShopOrderList(mOrderId)
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(mDatabind.ivBack, mDatabind.shopOrderConfirmReceived, mDatabind.shopOrderDeleteModify) {
            when (it) {
                mDatabind.shopOrderConfirmReceived -> {//确认收货
                    showReceivedGoodsDialog()
                }

                mDatabind.ivBack -> {
                    nav().navigateUp()
                }

                mDatabind.shopOrderDeleteModify -> {
                    when (mOrderStatus) {
                        2 -> {
                            nav().navigateAction(R.id.action_to_fragment_modify_order, Bundle().apply {
                                putInt("orderId", mOrderId.toInt())
                            })
                        }

                        3 -> {
                            nav().navigateAction(R.id.action_to_fragment_logistics_progress, Bundle().apply {
                                putString("expressNo", expressNo)
                                putInt("orderId", mOrderId.toInt())
                            })
                        }
                    }
                }
            }
        }
    }

    /** 确认收货弹窗 */
    private fun showReceivedGoodsDialog() {
        val dialog = RxDialogDefault(context)
        dialog.setTitle("是否确定收到货物？")
        dialog.setSureListener {
            showLoading(getString(R.string.loading))
            val body = AddOrReGoodsParam(id = mOrderId.toInt())
            mViewModel.confirmShopReceipt(body)
            dialog.dismiss()
        }
        dialog.setFullScreenWidth()
        dialog.show()
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun createObserver() {
        super.createObserver()
        /** 确认收货 */
        mViewModel.confirmReceivedResult.observe(viewLifecycleOwner) {
            if (it.isSuccess) {
                RxToast.showToast("已确认收货")
                /** 收货成功，通知刷新列表列表 */
                eventViewModel.toNoticeReceivedGoods.value = true
                nav().navigateAction(R.id.action_to_fragment_order_detail_finish, Bundle().apply {
                    putString("orderId", mOrderId)
                    putString("type", "2")//等待收获页跳入
                })
            } else {
                RxToast.showToast(it.errorMsg)
            }
        }
        /** 申请退款 */
        mViewModel.refundResult.observe(viewLifecycleOwner) {
            dismissLoadingAntiShake()
            if (it.isSuccess) {
                eventViewModel.refundReturnResult.value = true
                onRefresh()
            } else {
                RxToast.showToast(it.errorMsg)
            }
        }
        mViewModel.orderDetailResult.observe(viewLifecycleOwner) {
            dismissLoadingAntiShake()
            if (it != null) {
                refreshUIData(it)
            }
        }
    }

    @SuppressLint("NotifyDataSetChanged", "SetTextI18n")
    private fun refreshUIData(it: ConfirmAnOrderResponse) {
        mDatabind.data = it
        expressNo = it.expressNo
        mOrderStatus = it.orderStatus
        when (mOrderStatus) {
            2 -> {
                mDatabind.shopOrderDeleteModify.text = "修改订单"
                mDatabind.shopOrderApplyRefund.text = "申请退款"
            }

            3 -> {
                mDatabind.shopOrderDeleteModify.text = "物流进度"
                mDatabind.shopOrderApplyRefund.text = "申请退货"
            }
        }

        totalPrice = it.finalPrice.toString()
        SettingUtil.setPrice(totalPrice, mDatabind.tvOrderDetailFinalPrice, 60, Color.parseColor("#F44336"))
        if (!it.isEmpty()) {
            mAdapter.setList(it.list)
            mAdapter.notifyDataSetChanged()
        }
    }

    @SuppressLint("MissingInflatedId", "NotifyDataSetChanged")
    private fun showBottomDialogReason(goodsId: Int, orderId: Int, shopId: Int) {
        val mList = ArrayList<ReasonListBean>()
        mList.add(ReasonListBean("7天无理由"))
        mList.add(ReasonListBean("商品与页面描述不符"))
        mList.add(ReasonListBean("少件/发错货/未收到货"))
        mList.add(ReasonListBean("价格变化"))
        mList.add(ReasonListBean("商品破损/包装问题"))
        mList.add(ReasonListBean("商品质量/故障"))

        dialogBottom = context?.let { BottomSheetDialog(it, R.style.BottomSheetDialog) }!!
        val dialogView: View = LayoutInflater.from(context).inflate(R.layout.bottom_return_goods_reason, null)
        val swipeRecyclerView = dialogView.findViewById<SwipeRecyclerView>(R.id.swipeRecyclerView)
        val tvReturnGoodReason = dialogView.findViewById<AppCompatTextView>(R.id.tvReturnGoodReason)
        val ivCloseBottomDialog = dialogView.findViewById<AppCompatImageView>(R.id.ivCloseBottomDialog)

        swipeRecyclerView.init(LinearLayoutManager(context), mAdapterReason)
        swipeRecyclerView.adapter = mAdapterReason
        mAdapterReason.setList(mList)
        mAdapterReason.notifyDataSetChanged()

        var reasonContent = ""//退款原因
        mAdapterReason.setOnItemCheckClickListener(object : ReturnGoodsReasonAdapter.OnItemCheckClickListener {
            override fun onItemClick(position: Int) {
                reasonContent = mAdapterReason.data[position].reason
            }
        })

        tvReturnGoodReason.setOnClickListener {
            applyRefundReturn(reasonContent, goodsId, orderId, shopId)
        }
        ivCloseBottomDialog.setOnClickListener {
            dialogBottom.dismiss()
        }
        dialogBottom.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        dialogBottom.setContentView(dialogView)
        dialogBottom.show()
    }

    /**  申请退换货(退款) */
    private fun applyRefundReturn(reasonContent: String, goodsId: Int, orderId: Int, shopId: Int) {
        when (mOrderStatus) {
            2 -> {//退款
                if (reasonContent.isEmpty()) {
                    RxToast.showToast("请选择退款原因")
                    return
                }
                val body = RefundReturnParam(
                    reason = reasonContent,
                    damage = 2,//未损坏
                    goodsId = goodsId.toString(),
                    orderId = orderId,
                    shopUserId = shopId,
                    reviewType = 1,//退款
                    type = 1,
                )
                showLoadingAntiShake(getString(R.string.loading))
                mViewModel.addReturnReview(body)
                dialogBottom.dismiss()
            }

            3 -> {//退货
                dialogBottom.dismiss()
                nav().navigateAction(R.id.action_to_fragment_return_of_goods, Bundle().apply {
                    putInt("orderId", mOrderId.toInt())
                    putInt("shopUserId", shopId)
                    putString("goodsId", goodsId.toString())
                })
            }
        }
    }
}